# -*- coding: utf-8 -*-
from getMysqlData import getMysqlData
from getMysqlDataBigData import getMysqlDataBigData
from mysqlIndustryClass import mysqlIndustryClass
from agentCompanyInfo import agentCompanyInfo
from agentIndustryClass3C1 import agentIndustryClass3C1
from agentIndustryClass3C1Other import agentIndustryClass3C1Other
from agentIndustryClass3C3 import agentIndustryClass3C3
from agentIndustryClass3C4 import agentIndustryClass3C4
from agentIndustryClass3QA import agentIndustryClass3QA
from industryClassLib import allIndustryClass3, industryClass3Class1_13
from agentMajorProduct import agentMajorProduct
from agentIndustryClassBinary import agentIndustryClassBinary
import time

# 配置
useWebIndustryClassCash = False  # 使用网页提取的关键信息缓存


class makeLabel():
    def __init__(self):
        self.dbData = getMysqlData()
        self.dbBigData = getMysqlDataBigData()
        self.agentCompanyInfo = agentCompanyInfo()
        self.dbIndustryClass = mysqlIndustryClass()
        self.agentIndustryClass3C1 = agentIndustryClass3C1()
        self.agentIndustryClass3C1Other = agentIndustryClass3C1Other()
        self.agentIndustryClass3C3 = agentIndustryClass3C3()
        self.agentIndustryClass3C4 = agentIndustryClass3C4()
        self.agentMajorProduct = agentMajorProduct()
        self.agentIndustryClassBinary = agentIndustryClassBinary()
        self.agentIndustryClass3QA = agentIndustryClass3QA()

    def progressByBackCompanyName(self, industryClass3, companyName, QAFlag=True):
        res = ""
        logs = ""
        explain = ""
        logs += "【%s】\n" % companyName
        self.website, isOfficialWebsite, product, business, industry = "", "", "", "", ""
        # 打标表数据（缓存）或从爬虫表获取
        if useWebIndustryClassCash:
            # 打标表中依赖数据
            r = self.dbIndustryClass.getWebInfoByCompanyName(companyName)
            self.website, isOfficialWebsite, product, business, industry = r[0], r[1], r[2], r[3], r[4]
            logs += "公司网页：%s\n" % (str(self.website))
            logs += "-> 打标表数据（缓存）\n"
            isOfficialWebsite = "是" if isOfficialWebsite == 1 else "否"
        else:
            # 多渠道爬取产品结果汇总
            webText, self.website, sourceCount = self.dbData.getSpiderInfo(companyName)
            if webText and (len(webText) > 0) and (webText != "未提及"):
                logs += "-> 爬虫表数据\n"
                # 网页与产品数据提取
                logs += "数据源(%s)，文字数(%s)，网址(%s)\n" % (sourceCount, len(webText), self.website)
                logs += "-> Agent（根据网页抽取产品）：\n"
                # print("开始调用agent")
                companyInfo = self.agentCompanyInfo.progress(companyName, self.website, webText)
                # print("结束调用agent")
                isOfficialWebsite = companyInfo["是否官网"]
                product = companyInfo["公司产品"]
                business = companyInfo["主营业务"]
                industry = companyInfo["主要行业"]
                creditCode = self.dbBigData.getCompanyCreditCode(companyName)
                # 结果写到打标表
                self.dbIndustryClass.setWebInfoByCompanyName(companyName, creditCode, self.website,
                                                             True if isOfficialWebsite == "是" else False, product,
                                                             business, industry)
            else:
                logs += "-> 爬虫表数据（无！）\n"
                # 结果写到打标表
                self.dbIndustryClass.setWebInfoByCompanyName(companyName, None, None, None, None, None, None)
        # 置信度分支
        if len(product) > 0 or len(business) > 0:
            logs += "是否官网：%s\n公司产品：%s\n主营业务：%s\n主要行业：%s\n" % (isOfficialWebsite, product, business, industry)
            if len(product) > 0 and (product != "未提及"):
                if (len(business) > 0 and (business != "未提及")) or (len(industry) > 0 and (industry != "未提及")):
                    # 有产品，产品整理
                    product, log = self.agentMajorProduct.progress(companyName, product, business, industry)
                    if log:
                        logs = logs + log + "\n"
                    logs += "产品整理后：%s\n" % product
                else:
                    if len(product.split(";")) > 30:
                        product = ";".join(product.split(";")[:30])
                        logs += "产品数量过多截断到30个：%s\n" % product
                # 区分行业大类
                majorClass, log = self.agentIndustryClassBinary.progress(companyName, product, business, industry)
                if log:
                    logs = logs + log + "\n"
                logs += "行业大类：%s\n" % majorClass
            # 【置信度1】：官网，有产品
            if isOfficialWebsite == "是" and len(product) > 0 and (product != "未提及"):
                certainty = 1
                if majorClass == "制造与科技类":
                    res, explain, log = self.agentIndustryClass3C1.progressMultiStepByProduct(industryClass3,
                                                                                              companyName, product,
                                                                                              business, industry)
                else:
                    res, explain, log = self.agentIndustryClass3C1Other.progress(industryClass3Class1_13, companyName,
                                                                                 product, business, industry)
            # 【置信度2】：非官网，有产品
            elif len(product) > 0 and (product != "未提及"):
                certainty = 2
                if majorClass == "制造与科技类":
                    res, explain, log = self.agentIndustryClass3C1.progress(industryClass3, companyName, product,
                                                                            business, industry)
                else:
                    res, explain, log = self.agentIndustryClass3C1Other.progress(industryClass3Class1_13, companyName,
                                                                                 product, business, industry)
            # 【置信度3】：无产品，有相关网页
            elif len(business) > 0 and (business != "未提及"):
                certainty = 3
                res, explain, log = self.agentIndustryClass3C3.progress(industryClass3, companyName, business, industry)
            # 【置信度4】：无产品，网页无有效内容
            else:
                certainty = 4
        else:
            certainty = 4
        if certainty == 4:
            logs += "-> 大数据表数据\n"
            res = self.dbBigData.progress(companyName)
            gmIndustryClass = res[0]
            liandoIndustryClass = res[1]
            businessScope = res[2]
            logs += "大数据库（大数据库）：国民行业：%s\n自建行业（大数据库）：%s\n" % (gmIndustryClass, str(liandoIndustryClass))
            res, explain, log = self.agentIndustryClass3C4.progress(industryClass3, companyName, gmIndustryClass,
                                                                    liandoIndustryClass)  # 暂不使用businessScope
        logs += "-> Agent（行业打标）\n"
        logs += "置信度%s\n" % (certainty)
        logs = logs + log + "打标结果:%s\n" % res

        # 质检
        if res and (QAFlag == True):
            logs += "-> Agent（行业打标质检）：\n"
            annotationDict = {}
            checkLableList = res.keys()
            for k in checkLableList:
                v = self.dbIndustryClass.getIndustryAnnotation(k)
                annotationDict[k] = v
            r, log = self.agentIndustryClass3QA.progress(companyName, product, business, industry, annotationDict,
                                                         checkLableList)
            logs = logs + log + "质检结果:%s\n" % r
            # 还原回res格式
            res2 = {}
            if r:
                for k in r.split(";"):
                    res2[k] = res[k]
            res = res2
            # @TODO，可解释性中，质检去掉的结果要去掉对应的产品
        return certainty, res, explain, logs


if __name__ == "__main__":
    makeLabel = makeLabel()
    c, r, explain, logs = makeLabel.progressByBackCompanyName(allIndustryClass3, "成都休喻世软件开发工作室", QAFlag=True)
    print(logs)
    print(r)
    # print(explain)

    # # 写入数据库
    # from tools import industryClass3To2
    # from tools import industryClass3To1
    # dbIndustryClass = mysqlIndustryClass()
    # certainty, r, explain, logs = c,r,explain,logs
    # result_str = str(r).replace('"', "'").replace(" ", "")
    # dbIndustryClass.setIndustryClassByCompanyName("无锡睿诚和创自动化科技有限公司", industryClass3To1(r, True), industryClass3To2(r, True), result_str, explain, certainty, 0.0)

    # 测试用例
    # C1 无锡睿诚和创自动化科技有限公司  广州市凌捷医疗器械有限公司  三菱电机电力机电装备（北京）有限公司
    # C2 佛山市乾威斯雅电子科技有限公司  上海克莉丝汀食品有限公司   上海喆洋实业有限公司  上海山昆商贸发展有限公司杭州分公司   上海崇盟商贸有限公司   上海崇盟商贸有限公司
    # C3 万向集团公司  三地唛克斯科技（常州）有限公司  三绿源化工（广州）有限公司
    # C4 成都休喻世软件开发工作室 广州玛士家具有限公司
    # 上海谦毅达生物科技有限公司
